const _ = require('lodash');
const uuidv4 = require('uuid/v4');
const fs = require('fs');
const userInfoModel = require('../../app/models/userInfo.json');

module.exports={
    getUserInfoByUserId:getUserInfoByUserId,
    getUserInfoByName:getUserInfoByName,
    adduserInfo:adduserInfo
}


function getUserInfoByUserId(userId,callback){
    let result = null;
    _.forEach(userInfoModel,(item)=>{
        if(_.isEqual(userId,item.userId)){
            result = item;
        }
    });
    callback(null,result);
}

function getUserInfoByName(name,callback){
    let result = null;
    _.forEach(userInfoModel,(item)=>{
        if(_.isEqual(name,item.userName)){
            result = item;
        }
    });
    callback(null,result);
}

function adduserInfo(item,callback){
    item.itemId = uuidv4();
    let date = new Date().toLocaleString();
    item.createDatetime = date;
    item.updateDatetime = date;
    item.isSupport = false;
    userInfoModel.push(item);
    refreshDB(userInfoModel,(error)=>{
        callback(error,item);
    })
    
}

function refreshDB(data,callback){
    fs.writeFile('./app/models/userInfo.json',JSON.stringify(data,null,4),(error)=>{
        callback(error);
    });
}